package com.chen.common.satoken;

import cn.dev33.satoken.sso.function.SendHttpFunction;
import com.chen.common.satoken.component.SaApiName;
import com.chen.common.satoken.component.SaTokenSqlCurrUser;
import com.chen.common.satoken.config.SaTokenExceptionHandler;
import com.chen.common.satoken.config.SaTokenWebMvcConfig;
import com.dtflys.forest.Forest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: ChenJinLong
 * @DATE: 2025/1/7
 **/
@Slf4j
@Configuration
public class SaTokenAutoConfig {

    @Bean
    public SaApiName saApiName(){
        return new SaApiName();
    }

    @Bean
    public SaTokenWebMvcConfig saTokenWebMvcConfig(){
        return new SaTokenWebMvcConfig();
    }

    @Bean
    public SaTokenExceptionHandler saTokenExceptionHandler(){
        return new SaTokenExceptionHandler();
    }

    @Bean
    public SaTokenSqlCurrUser saTokenSqlCurrUser(){
        return new SaTokenSqlCurrUser();
    }

    public static SendHttpFunction sendHttpFunction(){
        return url -> {
            // 使用 try-catch 是为了提高整个注销流程的容错性，
            // 避免在一些极端情况下注销失败（例如：某个 Client 端上线之后又下线，导致 http 请求无法调用成功，从而阻断了整个注销流程）
            String resStr = "";
            try {
                log.info("------ 发起请求: \n{}", url);
                resStr = Forest.post(url).executeAsString();
                log.info("------ 请求结果: \n{}", resStr);
            } catch (Exception e) {
                log.error("", e);
            }
            return resStr;
        };
    }
}
